import { RedPacketType, useSetting } from "./utils/useSetting"
import { useStorage } from "./utils/useStorage"

declare const JavaAdapter: any;
declare const android: any;

export function renderZbIndex() {

    const setting = useSetting()

    if (!Array.isArray(setting.type)) {
        setting.type = [
            setting.type
        ].filter(it => !!it)
    }

    ui.layout(`<LinearLayout  layout_width="match_parent" layout_height="match_parent" orientation="vertical" paddingLeft="4sp" paddingRight="4sp">
    
        <ScrollView layout_width="match_parent" layout_height="wrap_content" paddingTop="4sp">
            <LinearLayout layout_width="match_parent" layout_height="wrap_content" orientation="vertical" paddingTop="4sp">
                <TextView layout_width="wrap_content" layout_height="wrap_content" textSize="14sp" text="是否已登录账号" paddingTop="4sp"/>
                <RadioGroup layout_width="match_parent" layout_height="wrap_content" orientation="horizontal" id="isTakeRedInfo">
                    <RadioButton text="是" id="isTakeRedInfo_yes" checked="${setting.isTakeRedInfo}" />
                    <RadioButton text="否" id="isTakeRedInfo_no" checked="${!setting.isTakeRedInfo}" />
                </RadioGroup>
                <TextView layout_width="match_parent" layout_height="wrap_content" textSize="14sp" text="目标红包个数" paddingTop="4sp"/>
                <EditText inputType="number" hint="请输入目标红包个数：如10000" text="${setting.totalCount}" layout_width="match_parent" layout_height="wrap_content" id="totalCount" />
                
                <TextView layout_width="wrap_content" layout_height="wrap_content" textSize="14sp" text="抓包类型" paddingTop="4sp"/>
                <LinearLayout layout_width="match_parent" layout_height="wrap_content" orientation="vertical" id="type">
                    <CheckBox text="穿云箭" id="type_0" checked="${setting.type.includes('穿云箭')}" />
                    <CheckBox text="快币" id="type_1" checked="${setting.type.includes('快币')}" />
                    <CheckBox text="口令" id="type_2" checked="${setting.type.includes('口令')}" />
                    <CheckBox text="粉丝团" id="type_3" checked="${setting.type.includes('粉丝团')}" />
                    <CheckBox text="观众包" id="type_4" checked="${setting.type.includes('观众包')}" />
                    <CheckBox text="分享" id="type_5" checked="${setting.type.includes('分享')}" />
                </LinearLayout>
    
                <TextView layout_width="wrap_content" layout_height="wrap_content" textSize="14sp" text="抓包来源" paddingTop="4sp"/>
                <RadioGroup layout_width="match_parent" layout_height="wrap_content" orientation="vertical" id="from">
                    <RadioButton text="直播" id="from_1" checked="${setting.from === '直播'}" />
                    <RadioButton text="关注" id="from_3" checked="${setting.from === '关注'}" />
                </RadioGroup>
    
                <TextView layout_width="wrap_content" layout_height="wrap_content" textSize="14sp" text="场景分类" paddingTop="4sp"/>
                <RadioGroup layout_width="match_parent" layout_height="wrap_content" orientation="vertical" id="category">
                    <RadioButton text="监控" id="category_0" checked="${setting.category === '监控'}" />
                    <RadioButton text="抓包" id="category_1" checked="${setting.category === '抓包'}" />
                </RadioGroup>
    
                <TextView layout_width="match_parent" layout_height="wrap_content" textSize="14sp" text="刷新间隔" paddingTop="4sp"/>
                <EditText inputType="number" hint="刷新间隔：10s" text="${setting.refreshInterval}" layout_width="match_parent" layout_height="wrap_content" id="refreshInterval" />
                
                <button style="Widget.AppCompat.Button.Colored" text="立即开始" id="start"></button>
                <button text="结束应用" id="stop"></button>
            </LinearLayout>
        </ScrollView>
    </LinearLayout>`)

    const start = ui.findView("start")
    const stop = ui.findView("stop")
    const root = files.cwd()

    ui.findView("isTakeRedInfo_yes").on("click", updateIsTakeRedInfo)
    ui.findView("isTakeRedInfo_no").on("click", updateIsTakeRedInfo)

    /**
     * 是否登录账号
     */
    function updateIsTakeRedInfo() {
        try {
            const typeid = ui.findView('isTakeRedInfo').getCheckedRadioButtonId()
            switch (typeid) {
                case ui.findView('isTakeRedInfo_yes').id:
                    setting.isTakeRedInfo = true
                    break;

                case ui.findView('isTakeRedInfo_no').id:
                    setting.isTakeRedInfo = false
                    break;
                default:
                    break;
            }
            useStorage().put('setting', setting);
        } catch (e) {
            console.error((e as Error).toString())
        }
    }

    function unique(type: RedPacketType[]) {
        let items: RedPacketType[] = []
        new Set(type).forEach(it => items.push(it))
        return items
    }
    /**
     * 更新抓包类型
     */
    function updateType(id: string, type: RedPacketType) {
        return () => {
            const view = ui.findView(id)
            try {
                if (!Array.isArray(setting.type)) {
                    setting.type = [setting.type]
                }
                const ischecked = setting.type.includes(type)
                if (ischecked) {
                    setting.type = setting.type.filter(it => it !== type)
                } else {
                    setting.type = unique([
                        ...setting.type,
                        type
                    ])
                }
                useStorage().put('setting', setting);
            } catch (e) {
                console.error((e as Error).toString())
            }
        }
    }

    ui.findView('type_0').on('click', updateType('type_0', '穿云箭'))
    ui.findView('type_1').on('click', updateType('type_1', '快币'))
    ui.findView('type_2').on('click', updateType('type_2', '口令'))
    ui.findView('type_3').on('click', updateType('type_3', '粉丝团'))
    ui.findView('type_4').on('click', updateType('type_4', '观众包'))
    ui.findView('type_5').on('click', updateType('type_5', '分享'))
    /**
     * 更新抓包来源
     */
    function updateFrom() {
        try {
            const typeid = ui.findView('from').getCheckedRadioButtonId()
            switch (typeid) {
                case ui.findView('from_0')?.id:
                    setting.from = '小时榜'
                    break;

                case ui.findView('from_1')?.id:
                    setting.from = '直播'
                    break;

                case ui.findView('from_2')?.id:
                    setting.from = '同城'
                    break;

                case ui.findView('from_3')?.id:
                    setting.from = '关注'
                    break;

                case ui.findView('from_4')?.id:
                    setting.from = '发现'
                    break;

                case ui.findView('from_5')?.id:
                    setting.from = '侧边栏'
                    break;

                default:
                    break;
            }
            useStorage().put('setting', setting);
        } catch (e) {
            console.error((e as Error).toString())
        }
    }

    ui.findView('from_0')?.on('click', updateFrom)
    ui.findView('from_1')?.on('click', updateFrom)
    ui.findView('from_2')?.on('click', updateFrom)
    ui.findView('from_3')?.on('click', updateFrom)
    ui.findView('from_4')?.on('click', updateFrom)
    ui.findView('from_5')?.on('click', updateFrom)


    function updateCategory() {
        try {
            const typeid = ui.findView('category').getCheckedRadioButtonId()
            switch (typeid) {
                case ui.findView('category_0').id:
                    setting.category = '监控'
                    break;
                case ui.findView('category_1').id:
                    setting.category = '抓包'
                    break;
                default:
                    break;
            }
            useStorage().put('setting', setting);
        } catch (e) {
            console.error((e as Error).toString())
        }
    }
    ui.findView('category_0').on('click', updateCategory)
    ui.findView('category_1').on('click', updateCategory)


    const textWatcherFactory = (field: string) => JavaAdapter(android.text.TextWatcher, {
        afterTextChanged: function (s: any) { },
        beforeTextChanged: function (s: string, start: number, count: number, after: number) { },
        onTextChanged: function (s: string, start: number, before: number, count: number) {
            try {
                (setting as any)[`${field}`] = parseInt(s.toString().trim())
                useStorage().put('setting', setting);
            } catch (e) {
                console.error(e)
            }
        }
    })

    const totalCountTextWatcher = textWatcherFactory('totalCount')
    const refreshIntervalTextWatcher = textWatcherFactory('refreshInterval')
    ui.findView("totalCount").addTextChangedListener(totalCountTextWatcher)
    ui.findView("refreshInterval").addTextChangedListener(refreshIntervalTextWatcher)

    start?.on("click", () => {
        engines.execScriptFile(files.join(root, "task.js"))
        events.emit('start', true)
    })

    stop?.on("click", () => {
        try {
            engines.stopAll()
        } catch (e: any) {
            console.error(e)
        }
    })
}
